package com.example.denglu.servlet;

import com.example.denglu.service.UserService;
import com.example.denglu.util.SmsUtil;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/sendCode")
public class SendCodeServlet extends HttpServlet {
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws IOException {
        String phone = request.getParameter("phone");
        String type = request.getParameter("type"); // register, reset, login
        
        response.setContentType("application/json;charset=utf-8");
        
        try {
            // 根据不同类型验证手机号
            if ("register".equals(type)) {
                if (UserService.isPhoneRegistered(phone)) {
                    response.getWriter().write("{\"success\":false,\"message\":\"该手机号已被注册\"}");
                    return;
                }
            } else if ("reset".equals(type)) {
                if (!UserService.isPhoneRegistered(phone)) {
                    response.getWriter().write("{\"success\":false,\"message\":\"该手机号未注册\"}");
                    return;
                }
            }
            
            // 检查是否频繁发送
            HttpSession session = request.getSession();
            Long lastSendTime = (Long) session.getAttribute(phone + "_lastSendTime");
            if (lastSendTime != null && System.currentTimeMillis() - lastSendTime < 60000) {
                response.getWriter().write("{\"success\":false,\"message\":\"请等待60秒后再次发送\"}");
                return;
            }
            
            // 手机号格式验证
            if (!SmsUtil.isValidPhoneNumber(phone)) {
                response.getWriter().write("{\"success\":false,\"message\":\"手机号格式不正确\"}");
                return;
            }
            
            // 生成验证码
            String code = SmsUtil.generateCode();
            System.out.println("生成的验证码：" + code);
            
            // 模拟发送验证码
            boolean isSent = SmsUtil.sendSms(phone, code);
            
            if (isSent) {
                // 保存验��码和发送时间
                session.setAttribute(phone + "_code", code);
                session.setAttribute(phone + "_lastSendTime", System.currentTimeMillis());
                session.setMaxInactiveInterval(300); // 5分钟有效期
                
                System.out.println("验证码已保存到session，key=" + phone + "_code" + ", value=" + code);
                response.getWriter().write("{\"success\":true,\"message\":\"验证码发送成功\"}");
            } else {
                response.getWriter().write("{\"success\":false,\"message\":\"验证码发送失败，请稍后重试\"}");
            }
        } catch (RuntimeException e) {
            // 处理阿里云短信服务的特定异常
            response.getWriter().write("{\"success\":false,\"message\":\"" + e.getMessage() + "\"}");
        } catch (Exception e) {
            System.out.println("发送验证码异常：" + e.getMessage());
            e.printStackTrace();
            response.getWriter().write("{\"success\":false,\"message\":\"系统错误，请稍后重试\"}");
        }
    }
} 